import re
import sys
import time
# from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem, QFileDialog, QApplication
from untitled import Ui_MainWindow
from PyQt5.QtCore import QThread
import ProceDataLayer as PDL
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
import os
from commonData import ComData as cd


class MyMainForm(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle(cd.title + cd.version)
        self.button_in.clicked.connect(self.get_excel_folders)
        self.button_out.clicked.connect(self.get_out_folders)
        self.data_table.setRowCount(cd.table_row_count)
        self.btn_star.clicked.connect(self.star)
        self.btn_end.clicked.connect(self.end)
        self.radio_day.clicked.connect(self.check_type)
        self.radio_month.clicked.connect(self.check_type)
        self.data_width.textEdited.connect(self.set_width)
        self.data_dot.textEdited.connect(self.set_dot)

    def set_dot(self):
        cd.dot = self.data_dot.text()
        MyMainForm.set_data_table(self)

    def set_width(self):
        cd.width = self.data_width.text()
        MyMainForm.set_data_table(self)

    def check_type(self):  # 选中日 还是 月数据
        if self.radio_day.isChecked():
            cd.type_of_day_or_month = 'day'
        else:
            cd.type_of_day_or_month = 'month'
        MyMainForm.set_data_table(self)

    def set_data_table(self):
        cd.spss_data_format = {}
        self.data_table.clear()
        # 读取文件中第一个文件的表头数据
        fileName = cd.folder_in
        if fileName != "":  # 在有文件的情况下，以文件为标准
            file = fileName + "\\" + os.listdir(fileName)[0]
            wb = load_workbook(file)
            ws = wb[wb.sheetnames[0]]
            values = ws['A1:{}1'.format(get_column_letter(ws.max_column))][0]
            cd.ucl_line = [str(v.value) for v in values]  # 不管是日还是月，都是以

        else:
            if cd.type_of_day_or_month == 'day':
                cd.ucl_line = ['区站号', '省份', '站名', '经度', '纬度', '观测场拔海高度', '年', '月']
                for i in range(1, 32):
                    cd.ucl_line.append(str(i) + '日')
            else:
                cd.ucl_line = ['区站号', '省份', '站名', '经度', '纬度', '观测场拔海高度', '年']  # 月值数据没有月
                for i in range(1, 13):
                    cd.ucl_line.append(str(i) + '月')
        year_index = 6
        if fileName != "":
            last_num = str(values[-1].value)
            num = re.findall(r'(\d+)', last_num)[0]
            un_num = ""  # 默认为空
            try:
                last_num = int(last_num)  # 如果转换失败，则表示该字符串非纯数字，那么就可以
            except Exception as e:
                un_num = re.findall(r'([^\d]+)', last_num)[0]  # 非数字部分
            # print(num, un_num)
            num = int(num)
            if cd.type_of_day_or_month == "day":
                flag_num = 31  # 如果是日
            else:
                flag_num = 12  # 如果是月
            for i in range(num + 1, num + (flag_num - num + 1)):
                cd.ucl_line.append(str(i) + un_num)  # 数字+非数字，这是对于月和日而言的

        """根据第二列，判断对应的数据类型"""
        # type_of_head = {}
        # for item in cd.ucl_line:
        #     index = cd.ucl_line.index(item)
        #     temp_v = line2_values[index]
        #     try:
        #         temp_v = float(temp_v)  # 若无法强制转换，则异常捕捉表示为字符串
        #     except Exception as e:
        #         type_of_head[item] = '字符串'
        #     else:
        #         type_of_head[item] = '数字'
        # print(type_of_head)

        # if cd.type_of_day_or_month == 'day':
        for row in range(len(cd.ucl_line)):
            # print(cd.ucl_line[row])
            if cd.ucl_line[row].lower() == '区站号':
                MyMainForm.set_data_table_fun(self, row, 5, 0, '数字')
            elif cd.ucl_line[row].lower() in ['省份', 'province']:
                MyMainForm.set_data_table_fun(self, row, 4, 0, '字符串')
            elif cd.ucl_line[row].lower() in ['站名', 'name']:
                MyMainForm.set_data_table_fun(self, row, 8, 0, '字符串')
            elif cd.ucl_line[row] == '观测场拔海高度':
                MyMainForm.set_data_table_fun(self, row, 10, 2, '数字')
            elif cd.ucl_line[row].lower() in ['经度', 'x', '纬度', 'y']:
                MyMainForm.set_data_table_fun(self, row, 15, 6, '数字')
            elif cd.ucl_line[row].lower() in ['年', '月', 'month', 'year', 'm', 'y']:
                MyMainForm.set_data_table_fun(self, row, 10, 0, '数字')
            else:
                MyMainForm.set_data_table_fun(self, row, cd.width, cd.dot, '数字')

    def set_data_table_fun(self, row, height, dot, type):  # 待修改的row， 宽度， 小数位数
        self.data_table.setItem(row, 0, QTableWidgetItem(cd.ucl_line[row]))
        self.data_table.setItem(row, 1, QTableWidgetItem(type))
        self.data_table.setItem(row, 2, QTableWidgetItem(str(height)))
        self.data_table.setItem(row, 3, QTableWidgetItem(str(dot)))
        self.data_table.setItem(row, 4, QTableWidgetItem(' '))
        self.data_table.setItem(row, 5, QTableWidgetItem('无'))
        self.data_table.setItem(row, 6, QTableWidgetItem('无'))
        self.data_table.setItem(row, 7, QTableWidgetItem(str(height)))
        self.data_table.setItem(row, 8, QTableWidgetItem('左'))
        self.data_table.setItem(row, 9, QTableWidgetItem('名义'))
        self.data_table.setItem(row, 10, QTableWidgetItem('输入'))

    def get_excel_folders(self):
        fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace("/", "\\")
        if fileName != "":
            # self.data_table.clear()  # 每次选中新的文件后，都清除重新印制
            cd.folder_in = fileName  # 设定输入文件夹的名字
            self.line_file_in.setText(fileName)
            MyMainForm.set_data_table(self)
            out_folder = cd.folder_in[:2] + "\\spss转为dat输出文件夹"
            self.line_file_out.setText(out_folder)
            cd.folder_out = out_folder

    def get_out_folders(self):
        fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace("/", "\\")  # 获取气温or降水所在的文件夹的位置
        if fileName != '':
            self.line_out_folder.setText(fileName)
            cd.folder_out = fileName

    # @get_abnormal
    def star(self):
        # try:
        '''获取数据对应的宽度和小数位数'''
        for row in range(0, len(cd.ucl_line)):
            name = self.data_table.item(row, 0).text()
            _type_ = self.data_table.item(row, 1).text()
            width = self.data_table.item(row, 2).text()
            digit_num = self.data_table.item(row, 3).text()
            if name != "":
                cd.spss_data_format[name] = [_type_, width, digit_num]  # 依次写入宽度和小数位数
        # print(cd.spss_data_format)
        self.thread = MyThread()
        self.thread.start()  # start调用的是run
        # except Exception as e:
        #     print("异常信息:", e)

    def end(self):
        sys.exit(app.exec_())


class MyThread(QThread):

    def __init__(self):
        super(MyThread, self).__init__()

    def run(self):
        startTime = time.time()
        # try:
        PDL.Data().spss_to_data()
        # except Exception as e:
        #     print("出现异常: ", e)
        print("处理完毕, 用时%.2f秒,%.2f分钟" % (time.time() - startTime, (time.time() - startTime) / 60))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())
